package com.serverclient.cglib.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.FactoryBean;

import com.ning.http.client.Response;
import com.serverclient.cglib.annotation.ServiceBean;
import com.serverclient.cglib.bean.HttpService;
import com.serverclient.cglib.beanregister.ServiceMethodInterceptor;
import com.serverclient.cglib.enums.HttpMethod;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InterfaceMaker;

/**
 * Spring手动注入Bean不是注入一个实例，而是注入类模板
 * 通过实现FactoryBean接口并实现getObject以及getObjectType方法，Spring就可以在需要生成Bean时生成指定的类型的Bean
 */
@ServiceBean("serverCglibService")
public class ServerCglibService implements FactoryBean<ServerCglibService>{
	public static Map<String, HttpService> methodMap = new HashMap<String, HttpService>();
	static {
		methodMap.put("getUserInfo", new HttpService("http://127.0.0.1:9011/getUserInfo.do",HttpMethod.GET));
		methodMap.put("addUserInfo", new HttpService("http://127.0.0.1:9011/addUserInfo.do",HttpMethod.POST));
	}
	
	/**
	 * 需要拦截的方法
	 * @param method
	 * @param param
	 * @param header
	 * @return
	 */
	public Response request(String method,Object param,Map<String,String> header) {
		return null;
	}

	/**
	 * 告诉Spring需要生成的Bean实例
	 */
	@Override
	public ServerCglibService getObject() throws Exception {
		InterfaceMaker interfaceMaker = new InterfaceMaker(); 
		Enhancer enhancer = new Enhancer();  
		enhancer.setSuperclass(ServerCglibService.class); 
		enhancer.setInterfaces(new Class[]{interfaceMaker.create()});  
		enhancer.setCallback(new ServiceMethodInterceptor());
		return (ServerCglibService) enhancer.create();
	}

	@Override
	public Class<?> getObjectType() {
		return ServerCglibService.class;
	}
}
